/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <sf-form ref="form"
             class="add-interact-task__form"
             :label-width="130">
        <div class="form__type">
            <div class="form__title">
                <lang>基础信息</lang>
            </div>
            <sf-form-item>
                <sf-fieldlabel>
                    <lang>任务名称</lang>
                </sf-fieldlabel>
                <sf-textfield
                    ref="fieldName"
                    v-model="submitData.name"
                    :default-width="defaultWidth"
                    :max-length="30"
                    :allow-blank="false"
                    :utf8-length="false"
                    vtype="name_task"
                    :blur-trim="true" />
            </sf-form-item>
            <sf-form-item>
                <sf-fieldlabel>
                    <lang>描述</lang>
                </sf-fieldlabel>
                <sf-textarea
                    v-model="submitData.description"
                    :placeholder="_('最多300字（选填）')"
                    :default-width="defaultWidth"
                    :max-length="300"
                    :utf8-length="false" />
            </sf-form-item>
            <sf-form-item v-if="showAIFlowList">
                <sf-fieldlabel>
                    <lang>AI Flow</lang>
                </sf-fieldlabel>
                <sf-select v-model="flowId"
                           :default-width="defaultWidth"
                           class="pull-right m-r25"
                           :allow-search="true"
                           :allow-blank="false"
                           display-field="flowName"
                           value-field="aiFlowId"
                           :options="flowList" />
            </sf-form-item>
            <sf-form-item v-if="showAIFlowList">
                <sf-fieldlabel>
                    <lang>AI Flow版本</lang>
                </sf-fieldlabel>
                <sf-select v-model="flowVersionId"
                           :default-width="defaultWidth"
                           class="pull-right m-r25"
                           :allow-search="true"
                           :allow-blank="true"
                           display-field="version"
                           value-field="aiFlowId"
                           :options="flowVersionList" />
            </sf-form-item>
        </div>
        <div class="form__type ">
            <div class="form__title">
                <lang>调度配置</lang>
            </div>
            <sf-form-item class="flex-center">
                <sf-fieldlabel>
                    <lang>训练周期</lang>
                </sf-fieldlabel>
                <div>
                    <sf-radio-group 
                        v-model="type">
                        <sf-radio 
                            v-for="(item,index) in typeList"
                            :key="index"
                            name="type"
                            :check-value="item.type">
                            {{ item.name }}
                        </sf-radio>
                    </sf-radio-group>
                </div>
            </sf-form-item>
        </div>
        <div v-if="type!==0"
             class="period-time__wrap">
            <div class="period-time__content">
                <new-datefield ref="startTime"
                               v-model="startTime"
                               :placeholder="_('立即开始')"
                               :show-clear="true"
                               type="dateTime"
                               :clear-text="_('立即开始')"
                               :start-limit="startLimt"
                               :validator="checkIsLtEnd" />
                <span class="m-lr5"><lang>至</lang></span>
                <new-datefield ref="endTime"
                               v-model="endTime"
                               :placeholder="_('永不结束')"
                               :show-clear="true"
                               type="dateTime"
                               :start-limit="startLimt"
                               :clear-text="_('永不结束')"
                               :validator="checkIsGtStart" />
            </div>
            <div v-if="type===1"
                 class="period-time__content">
                <span class="m-r5"><lang>每隔</lang></span>
                <sf-numberfield ref="timeLength"
                                v-model="intervalPrefix"
                                :default-width="130"
                                :allow-blank="false"
                                :allow-decimals="false"
                                :placeholder="_('请输入整数')"
                                :validator="intervalPrefixVidator"
                                :min-value="1"
                                :max-value="100"
                                 />
                <sf-select v-model="intervalSuffix"
                           :default-width="130"
                           :allow-search="true"
                           :allow-blank="false"
                           class="m-r5"
                           :options="intervalSuffixList" />
                <span><lang>训练一次</lang></span>
            </div>
            <div v-if="type===2"
                 class="period-time__content">
                <span><lang>cron表达式</lang></span>
                <sf-textfield
                    ref="fieldName"
                    v-model="cron"
                    :default-width="236"
                    :allow-blank="false"
                    :utf8-length="false"
                    :blur-trim="true" />
            </div>
            <div
                class="period-time__content">
                <span><lang>最大并行任务数</lang></span>
                <sf-numberfield ref="taskNum"
                                v-model="maxConcurrency"
                                :default-width="130"
                                :allow-blank="false"
                                :allow-decimals="false"
                                :placeholder="_('请输入整数')"
                                :min-value="1"
                                :max-value="10" />
                <span><lang>个</lang></span>
            </div>
        </div>
        <div class="form__type">
            <div class="form__title">
                <lang>参数</lang>
            </div>
            <sf-form-item v-for="(item,index) in paramList"
                          :key="index">
                <sf-fieldlabel>
                    <lang>{{ item.name }}</lang>
                </sf-fieldlabel>
                <sf-textfield
                    ref="fieldName"
                    v-model="item.value"
                    :default-width="defaultWidth"
                    :max-length="30"
                    trigger-clear
                    :allow-blank="false"
                    :utf8-length="false"
                    :blur-trim="true" />
            </sf-form-item>
        </div>
    </sf-form>
</template>
<script>

 import {
    decodeDate,
    encodeDate
} from 'src/util/format';
const DEFAULT_WIDTH = 452;
const DEFAULT_VALUE = {
    name: '',
    description:'',
    interactiveFlowId:'',
    parameters:''
};
import newDatefield from 'src/components/new_datefield.vue';
import trainingUrlAdapter from 'src/home/mod_common/training_url_adapter';
export default {
    computed: {
        defaultWidth () {
            return DEFAULT_WIDTH;
        },
        projectId () {
            return this.$route.query.projectId || '';
        },
        startLimt(){
            let curDate = new Date();
            /* eslint-disable no-magic-numbers */
            let preDate = new Date(curDate.getTime() - 24*60*60*1000); // 前一天
            return preDate;
        }
    },
    components:{
        newDatefield
    },
    data () {
        return {
            fff:'',
            submitData: { ...DEFAULT_VALUE },
            flowList:[],
            flowId:'',
            flowVersionId:'',
            flowVersionList:[],
            paramList:[],
            trainingType:0,
            showAIFlowList:true,
            type:0,
            startTime:'',
            endTime:'',
            intervalPrefix:'1',
            intervalSuffix:'hour',
            // 算子时间单位
            intervalSuffixList :[
                {
                    label:_('分'),
                    value:'minute'
                },
                {
                    label:_('小时'),
                    value:'hour'
                }, {
                    label:_('天'),
                    value:'day'
                }, {
                    label:_('星期'),
                    value:'week'
                }, {
                    label:_('月'),
                    value:'month'
                }
            ],
            cron:'',
            typeList:[{
                type:1,
                name:_('周期间隔')
            }, {
                type:2,
                name:_('Cron')
            }],
            maxConcurrency:''
        };
    },
    watch: {
        flowId: {
            deep:true,
            handler () {

                // 隐藏的话，默认不改动参数列表
                if (this.showAIFlowList) {
                    this.paramList = this.flowList.find(item=>item.aiFlowId === this.flowId).parameters;
                    this.getFlowVersion();
                }
            }
        },
        flowVersionId: {
            deep:true,
            handler () {
                // 隐藏的话，默认不改动参数列表
                if (this.showAIFlowList) {
                    this.paramList = this.flowList.find(item=>item.aiFlowId === this.flowVersionId).parameters;
                }
            }
        },
        intervalSuffix: {
            deep:true,
            handler () {
                this.intervalSuffixValidate();
            }
        }
    },
    mounted () {
    },
    methods: {
        getJsonValue () {
            this.submitData.parameters = this.paramList;
            this.submitData.projectId = this.projectId;
            let type = this.type;
            this.submitData.type = type;
            // 如果为克隆任务，则取到的是flowId
            this.submitData.interactiveFlowId = this.showAIFlowList ? this.flowVersionId : this.flowId;
            // 如果为周期训练
            if (type !== 0) {
                this.submitData.startTime = this.startTime ? decodeDate(this.startTime).getTime() : '';
                this.submitData.endTime = this.endTime ? decodeDate(this.endTime).getTime() : '';
                this.submitData.maxConcurrency = this.maxConcurrency;
                if (type === 1) {
                    /* eslint-disable no-magic-numbers */
                    this.submitData.intervalPrefix = this.intervalPrefix;
                    this.submitData.intervalSuffix = this.intervalSuffix;
                } else {
                     this.submitData.cron = this.cron;
                }
            }
            return this.submitData;
        },
        setJsonValue (data) {
            if (data.type !== 0) {
                this.type = Number(data.type);
                this.startTime = data.startTime ? encodeDate(data.startTime) : '';
                this.endTime = data.endTime ? encodeDate(data.endTime) : '';
                this.intervalPrefix = data.intervalPrefix;
                this.intervalSuffix = data.intervalSuffix;
                this.cron = data.cron;
                this.maxConcurrency = data.maxConcurrency;
            }
            this.submitData = {...DEFAULT_VALUE, ...data};
        },
        timeRangeIsOk () {
            if (this.startTime && this.endTime) {
                return decodeDate(this.startTime).getTime() <= decodeDate(this.endTime).getTime();
            }
            return true;
        },
        checkIsLtEnd () {
            if (!this.timeRangeIsOk()) {
                return _('开始时间不能大于结束时间！');
            }

            this.$refs.endTime.clearInvalid();
            return true;
        },

        checkIsGtStart () {
            if (!this.timeRangeIsOk()) {
                return _('结束时间不能小于开始时间！');
            }

            this.$refs.startTime.clearInvalid();
            return true;
        },
        intervalSuffixValidate () {
            this.$nextTick().then(()=>{
                if (!this._getUpdateTimeFlag(this.intervalPrefix)) {
                    this.$refs.timeLength && this.$refs.timeLength.validate();
                } else {
                    this.$refs.timeLength && this.$refs.timeLength.clearInvalid();
                }
            });
        },
        intervalPrefixVidator (value) {
            if (!value) {
                return _('该输入项不允许为空');
            }
            if (!this._getUpdateTimeFlag(value)) {
                return _('训练时间不能大于选择时间区间');
            }
            return true;
        },
        getUpdateTime (value) {
            let unit = this.intervalSuffix;
            let updateTime;
            value = Number(value);

            /* eslint-disable no-magic-numbers */
            if (unit === 'month') {
                updateTime = 1000 * 60 * 60  * 24 * 30 * value;
            } else if (unit === 'week') {
                updateTime = 1000 * 60 * 60 * 24 * 7 * value;
            } else if (unit === 'day') {
                updateTime = 1000 * 60 * 60  * 24 * value;
            } else if (unit === 'hour') {
                updateTime = 1000 * 60 * 60 * value;
            } else {
                updateTime = 1000 * 60 * value;
            }
            return updateTime;
        },
        _getUpdateTimeFlag (value) {

            // 立即结束，不需要做判断
            if (!this.endTime) {
                return true;
            };

            // 如果是立即开始，则间隔为0
            let startTime = this.startTime ? decodeDate(this.startTime).getTime() : new Date().getTime();
            let executionTime = decodeDate(this.endTime).getTime() - startTime;

            // 更新时间
            let updateTime = this.getUpdateTime(value);
            if (updateTime > executionTime) {
                return false;
            }

            // debugger;
            return true;
        },
         async getFlowVersion () {
            this.$mask();
            const TRAINING_GET_URL = trainingUrlAdapter(`interactiveFlow/${this.flowId}/allVersion`);
            this.$unmask();
            let jsonData = await this.$ajax.get(TRAINING_GET_URL, this.searchParams);
            let {success, msg, data} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            };
            this.flowVersionList = data;
            this.flowVersionId = data[0].aiFlowId;
        },

        // _cronValidator (value) {
        //     window.console.log(isValidCron(value));

        //     // if (!isValidCron(value)) {
                
        //     //     // Do something
        //     //     return _('cron语法不正确，请重新输入');
        //     // }
        //     return true;
        // }

    }
};
</script>
<style lang="less">
.add-interact-task__form {
    max-height: 576px;
    overflow-y: auto;
    .line-32{
        line-height: 32px;
    }
    .sfv-form-item{
        margin-bottom: 12px;
    }
     .form__title{
        margin-bottom: 10px;
        margin-left: -8px;
        color: #14161a;
        font-weight: bold;
    }
    .period-time__wrap{
        background: #FAFAFA;
        border: 1px solid #E0E0E0;
        width: 456px;
        margin-left: 130px;
        padding: 10px 15px;
        padding-bottom: 0;
        margin-bottom: 10px;
        margin-top: -5px;
        .period-time__content{
            margin-bottom: 10px;
        }
    }
}
</style>
